package com.ve.s2g.service

import com.alibaba.fastjson.JSON
import com.ve.s2g.getLogger
import com.ve.s2g.pojo.GitlabProject
import com.ve.s2g.pojo.Project
import com.ve.s2g.util.HttpClientManager
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import org.springframework.stereotype.Service


@Service
class GitlabService {

    private val eagerClient: OkHttpClient? by lazy {
        HttpClientManager.getOkHttpClient()
    }

    fun searchProject(url: String): List<GitlabProject>? {
        val request = Request.Builder()
            .url(url)
            .build()
        val call = eagerClient?.newCall(request)
        val response1 = call!!.execute()
        return JSON.parseArray(response1.body()!!.string(), GitlabProject::class.java)
    }


    fun createProject(project: GitlabProject,url: String) : GitlabProject{
        val formBody = FormBody.Builder()
            .add("name", project.name)
            .build()
        val request = Request.Builder()
            .post(formBody)
            .url(url)
            .build()
        val response1 = eagerClient?.newCall(request)!!.execute()
        when (response1.code()) {
            200,201,202 -> {
                val jsonObject = JSON.parseObject(response1.body()!!.string())
                var result =GitlabProject(project.name)
                result.id = jsonObject.get("id") as Int
                getLogger<GitlabService>().info("${project.name} create success.")
                return result
            }
            else -> {
                val jsonObject = JSON.parseObject(response1.body()!!.string())
                throw Exception("create ${project.name} error.${jsonObject.toJSONString()}")
            }
        }

    }

    fun moveProject(project: Project, namespace: String, url: String){
        val formBody = FormBody.Builder()
            .add("namespace", namespace)
            .build()
        val request = Request.Builder()
            .put(formBody)
            .url(url)
            .build()
        val response1 = eagerClient?.newCall(request)!!.execute()
        when (response1.code()) {
            200,201,202 -> {
                getLogger<GitlabService>().info("${project.name} move success.")
            }
            else -> {
                val jsonObject = JSON.parseObject(response1.body()!!.string())
                throw Exception("move ${project.name} error.${jsonObject.toJSONString()}")
            }
        }
    }

    fun deleteProject(project: GitlabProject,url: String){

    }
}

